﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace PK10Server
{
    class serverSocket
    {
        public void StartServer()
        {
            Socket serverSk = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            serverSk.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8596));
            serverSk.Listen(1);

            SocketAsyncEventArgs AcceptSAE = new SocketAsyncEventArgs();
            AcceptSAE.Completed += new EventHandler<SocketAsyncEventArgs>(AcceptSAE_Completed);
            serverSk.AcceptAsync(AcceptSAE);

            Console.ReadLine();
        }

        static void AcceptSAE_Completed(object sender, SocketAsyncEventArgs e)
        {
            Socket serverSk = sender as Socket;
            if (e.SocketError == SocketError.Success)
            {
                serverSk = e.AcceptSocket;
                SocketAsyncEventArgs SendSAE = new SocketAsyncEventArgs();
                byte[] data = System.Text.Encoding.UTF8.GetBytes("OK,Just Put IT!");
                SendSAE.SetBuffer(data, 0, data.Length);
                SendSAE.Completed += new EventHandler<SocketAsyncEventArgs>(SendSAE_Completed);

                SocketAsyncEventArgs RecieveSAE = new SocketAsyncEventArgs();
                byte[] buffer = new byte[2048];
                RecieveSAE.SetBuffer(buffer, 0, buffer.Length);
                RecieveSAE.Completed += new EventHandler<SocketAsyncEventArgs>(RecieveSAE_Completed);

                serverSk.ReceiveAsync(RecieveSAE);
                serverSk.SendAsync(SendSAE);
            }
            else
                Console.WriteLine("接受网络套接字连接请求失败！具体原因请自己调试！");
                
        }

        static void RecieveSAE_Completed(object sender, SocketAsyncEventArgs e)
        {
            Socket sk = sender as Socket;
            byte[] data = e.Buffer;  //注意这里，如何取关联到套接字的发送接受的缓冲区中的值。
            string msg = System.Text.Encoding.UTF8.GetString(data);
            Console.WriteLine("Message received: " + msg);

            // sk.DisconnectAsync();//你看看 该怎么做呢？
        }

        static void SendSAE_Completed(object sender, SocketAsyncEventArgs e)
        {
            Socket sk = sender as Socket;
            if (e.SocketError == SocketError.Success)
            {
                Console.WriteLine("Send complete!");

                byte[] data = e.Buffer;  //注意这里，如何取关联到套接字的发送接受的缓冲区中的值。
                string msg = System.Text.Encoding.UTF8.GetString(data);
                Console.WriteLine("What you sent: " + msg);
            }
        }
    }
}
